<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/6/2 15:33
 */

namespace App\Transformers;

use App\Models\MedicalRecord;
use App\Models\Patient;
use Illuminate\Pagination\LengthAwarePaginator;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use League\Fractal\TransformerAbstract;

class PatientListTransformer extends TransformerAbstract
{
    /**
     * @var \App\Project\FieldTranslation\FieldTranslation
     */
    protected $field;

    public function __construct()
    {
        $this->field = app('field')->get('patient');
    }

    /**
     * @param \Illuminate\Pagination\LengthAwarePaginator $pagination
     * @return \League\Fractal\Resource\Collection
     */
    public function transform(LengthAwarePaginator $pagination)
    {
        $collection = $pagination->getCollection();

        $ids = $collection->pluck('id');

        $records = MedicalRecord::whereIn('patient_id', $ids->toArray())
                                ->select(['id', 'patient_id', 'clinic_at', 'visit_type'])
                                ->get()->groupBy('patient_id')->toArray();

        $collection = $collection->map(function (Patient $patient) use ($records) {

            $patient->records = $records[$patient->id];

            return $patient;
        });

        return $this->collection($collection, function (Patient $patient) {
            return $patient->toArray();
        })->setPaginator(new IlluminatePaginatorAdapter($pagination));
    }
}